package dao

import (
	"context"
	"gorm.io/gorm"
	"mall_2.0/respository/db/model"
	"mall_2.0/types"
)

type FavoriteDao struct {
	*gorm.DB
}

func NewFavoriteDao(ctx context.Context) *FavoriteDao {
	return &FavoriteDao{NewDBClient(ctx)}
}

func NewFavoriteDaoByBD(db *gorm.DB) *FavoriteDao {
	return &FavoriteDao{db}
}

// CreateFavorite 创建收藏夹
func (dao *FavoriteDao) CreateFavorite(favorite *model.Favorite) error {
	return dao.DB.Model(&model.Favorite{}).Create(&favorite).Error
}

// DeleteFavorite 删除收藏夹
func (dao *FavoriteDao) DeleteFavorite(fID uint) error {
	return dao.DB.Model(&model.Favorite{}).Where("id = ?", fID).Delete(&model.Favorite{}).Error
}

// FavoriteExistOrNot 判断收藏夹是否存在
func (dao *FavoriteDao) FavoriteExistOrNot(pID, uID uint) (exist bool, err error) {
	var count int64
	err = dao.DB.Model(&model.Favorite{}).Where("product_id = ? AND user_id = ?", pID, uID).Count(&count).Error
	if count == 0 || err != nil {
		return false, err
	}
	return true, nil
}

// ListFavoriteByUID 获取用户收藏夹列表
func (dao *FavoriteDao) ListFavoriteByUID(uID uint, page *types.BasePage) (r []*types.FavoriteListResp, total int64, err error) {
	err = dao.DB.Model(&model.Favorite{}).Preload("User").Where("user_id = ?", uID).Count(&total).Error
	if err != nil {
		return
	}
	err = dao.DB.Model(&model.Favorite{}).
		Joins("AS f LEFT JOIN user AS u ON u.id = f.boss_id").
		Joins("LEFT JOIN products AS p ON p.id = f.product_id").
		Joins("LEFT JOIN category AS c ON c.id = f.category_id").
		Where("f.user_id = ?", uID).
		Offset((page.PageNum - 1) * page.PageSize).
		Limit(page.PageSize).
		Select("f.user_id AS user_id," +
			"f.product_id AS product_id," +
			"UNIX_TIMESTAMP(f.created_at) AS created_at," +
			"p.title AS title," +
			"p.info AS info," +
			"p.name AS name," +
			"c.id AS category_id," +
			"c.category_name AS category_name," +
			"u.id AS boss_id," +
			"u.user_name AS boss_name," +
			"u.avatar AS boss_avatar," +
			"p.price AS price," +
			"p.img_path AS img_path," +
			"p.discount_price AS discount_price," +
			"p.num AS num," +
			"p.on_sale AS on_sale").
		Find(&r).Error

	return
}
